/*
 * LocalTask.cpp
 *
 *  Created on: 2010-11-21
 *      Author: leo
 */
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <iostream>

#include "LocalTask.h"

using namespace std;
using namespace boost;
using namespace boost::gregorian;//::day_clock;
using namespace boost::posix_time;

namespace GTD {

boost::mutex TaskIDGen::_mutex;
TaskID		TaskIDGen::_base;

bool TaskIDGen::genID(TaskID& id)
{
	//TODO review: protection in multi-threading env
	if (_mutex.try_lock()) {
//		_mutex.lock();
		id = _base++;
		_mutex.unlock();
		return true;
	} else
		return false;
}

bool	TaskIDGen::reloadBaseID()
{
	return false;
}

LocalTask::LocalTask(string t) 	: taskTitle(t), expire(false),
						startTime(second_clock::local_time()),
						endTime(startTime.date(), hours(24))
						{
	bool ret = TaskIDGen::genID(id);

	if (!ret) {
		// TODO: redo gen ID process
	}

}

LocalTask::LocalTask(string t, ptime st, ptime et) :
		taskTitle(t), expire(false),
		startTime(st), endTime(et)
{
	bool ret = TaskIDGen::genID(id);
	if (!ret) {
		// TODO: redo gen ID process
	}

}

LocalTask::~LocalTask() {
	// TODO Auto-generated destructor stub
}

time_duration LocalTask::stillLast()
{
	time_duration last(0, 0, 0);
	if (!expire) {
		ptime curr = second_clock::local_time();
		last = endTime - curr;
	#ifdef DEBUG
		cout << "task lasts " << last << endl;
	#endif
	}
	return last;
}

bool LocalTask::cancel()
{
	expire = true;
	//TODO: notify persons involved
	return false;
}

void	LocalTask::addPersonInvolved(Person p)
{
	// still can add person when task is expired.
	// TODO: if exists, do not add again.
	personInvolved.push_back(p);
}	

bool	earlier(LocalTask& t1, LocalTask& t2)
{
	bool	ret = false;
	if (t1.startTime < t2.startTime)
		ret = true;
	return ret;
}

}
